package org.jash.shop2111.product

import android.os.AsyncTask
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import org.jash.shop2111.entry.Goods
import org.jash.shop2111.mvvm.BaseViewModel
import org.jash.shop2111.utils.dao.GoodsDao
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import javax.inject.Inject

@HiltViewModel
class ProductViewModel @Inject constructor(val goodsDao: GoodsDao): BaseViewModel() {
    val goodsLiveData by lazy { MutableLiveData<List<Goods>>() }
    fun loadGoods(category_id:Int, currentPage:Int, pageSize:Int) {
        if (currentPage == 1) {
            val d = goodsDao.findByCategoryId(category_id).subscribe {
                goodsLiveData.postValue(it)
            }
            addCloseable { d.takeIf { !it.isDisposed }?.dispose() }
        }

        val disposable =
            service.getGoodsList(category_id, currentPage, pageSize)
                .subscribe({
                    if (it.code == 200 && it.data != null) {
                        val d = goodsDao.save(*it.data.toTypedArray()).subscribe {
                            Log.d("ProductViewModel", "loadGoods: 保存成功")
                        }
                        addCloseable { d.takeIf { !it.isDisposed }?.dispose() }
                        goodsLiveData.postValue(it.data)
                    } else {
                        errorLiveData.postValue(RuntimeException(it.message))
                    }
                }, errorLiveData::postValue)
        addCloseable { disposable.takeIf { !it.isDisposed }?.dispose() }
    }

}